var express = require('express');
var router = express.Router();

// 导入db, 操作数据库
const { getAll, getById, exec } = require('../db');

//get /users?page=1&size=5
router.get('/', async (req, res) => {
  //解析请求参数
  const { page = 1, size = 5 } = req.query;
  let sql = `select count(*) as total from users`;
  let { total } = await getById(sql); //获取总记录数
  console.log(total);

  //偏移量=(page-1)*size
  let offset = (page - 1) * size;
  //操作数据库
  sql = `select id,username,password from users limit ${offset},${size}`; //分页
  const data = await getAll(sql);
  res.send({
    code: 0,
    message: '获取所有用户成功',
    result: {
      total,
      data,
    },
  });
});

router.get('/:id', async (req, res) => {
  const { id } = req.params;

  let sql = `select * from users where id = ${id}`;
  const data = await getById(sql);
  res.send({
    code: 0,
    message: '获取单个用户成功',
    result: data,
  });
});

//post /users {username:'',passw:123456}
router.post('/', async (req, res) => {
  const { username, password } = req.body;

  let sql = `insert into users (username,password) value('${username}',${password})`;
  const { insertId } = await exec(sql);
  res.send({
    code: 0,
    message: '添加用户成功',
    result: {
      id: insertId,
      username,
      password,
    },
  });
});

router.put('/:id', async (req, res) => {
  const { id } = req.params;
  const { username, password } = req.body;

  let sql = `update users set username='${username}',password='${password}' where id=${id}`;
  await exec(sql);
  res.send({
    code: 0,
    message: '修改成功',
    result: {
      id,
      username,
      password,
    },
  });
});

module.exports = router;
